package com.jh.paymentchannel.service;

//import static org.hamcrest.CoreMatchers.nullValue;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jh.paymentchannel.pojo.JFApiRegister;
import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Objects;
import com.google.common.collect.Maps;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.jifuquick.AES;
import com.jh.paymentchannel.util.jifuquick.Base64;
import com.jh.paymentchannel.util.jifuquick.HttpClient4Util;

import cn.jh.common.tools.Log;
import net.sf.json.JSONObject;

@Controller
@EnableAutoConfiguration
public class JFAPIPageRequest {

	private static final Logger log = LoggerFactory.getLogger(JFAPIPageRequest.class);

	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;

	@Autowired
	private Util util;

	@Value("${payment.ipAddress}")
	private String ipAddress;
	
	@Value("${jfapi.partnerNo}")
	private String partnerNo;
	
	@Value("${jfapi.key}")
	private String Key;
	
	@Value("${jfapi.url}")
	private String JFurl;
	
	/*private static String partnerNo = "XL0APID0";

	private static String Key = "0123456789abcdefghijklmnopqrstuv";

	private String JFurl = "http://fast.jfpays.xyz:19084";*/

	private static final Charset UTF_8 = StandardCharsets.UTF_8;

	//前端开通接口
	@RequestMapping(method = RequestMethod.GET, value = "/v1.0/paymentchannel/topup/jfapiregister")
	public void returnapisuccess(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		// 设置编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		Map<String, String> map = new HashMap<String, String>();

		String userNames = request.getParameter("userNames");
		String bankCard = request.getParameter("bankCard");
		String mobile = request.getParameter("mobile");
		String idCard = request.getParameter("idCard");
		String ordercode = request.getParameter("ordercode");

		// 进件接口的交易代码
		String txnCode = "401001";
		String api = "/rest/api/" + txnCode;

		JSONObject dto = new JSONObject();

		dto.put("accNo", bankCard);// 银行卡号
		dto.put("cardHolderName", userNames);// 持卡人姓名
		dto.put("mobile", mobile);// 手机号
		dto.put("idCard", idCard);// 身份证号
		dto.put("frontUrl", ipAddress+"/v1.0/paymentchannel/topup/jfapi/openfront/notify_call");// 前台通知地址URL
		dto.put("backUrl", ipAddress+"/v1.0/paymentchannel/topup/jfapi/openfront/notify_call");// 后台通知地址URL

		dto.put("head", this.getHead(ordercode, partnerNo, txnCode));
		log.info("dto======" + dto);
		String execute = this.execute(Key, JFurl, api, dto.toString(), partnerNo, ordercode);
		log.info(execute);

		String res;
		// 返回状态码
		String respCode;
		String respMsg;
		String pageContent = "";
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			log.info("hahahha=========" + resJson);
			String sign = resJson.getString("signature");
			log.info("hahahha=========" + sign);
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));
			log.info("hahahha=========" + res);

			com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(res);

			com.alibaba.fastjson.JSONObject head = json.getJSONObject("head");
			respCode = head.getString("respCode");
			respMsg = head.getString("respMsg");
			pageContent = json.getString("pageContent");
		} catch (Exception e1) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jfapi");
			map.put("resp_message", "亲,失败啦");
		}
		Map mapp = new HashMap();

		log.info("pageContent=====" + pageContent);

		response.getWriter().println(pageContent);

	}

	
	//消费短信接口
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/paymentchannel/topup/jfapi/sendmessage")
	public @ResponseBody Object jfapisendmessage(HttpServletRequest request,
			 @RequestParam(value = "ordercode") String orderCode
			 )
			throws Exception {
		log.info("开始进入消费短信接口=====================");
//		银行卡号
		String bankCard = "";
//		银行卡类型
		String cardType = "0";
//		持卡人姓名
		String userName = "";
//		手机号
		String phone = "";
//		身份证号
		String certId = "";
//		用户Id
		String userId = "";
//		费率
		String rate = "";
		//额外费用
		String extraFee = "";
		String amount = "";
		
		log.info("传过来的订单号=========orderCode"+orderCode);
		
		Map<String,String> map = new TreeMap<String,String>();
		RestTemplate restTemplate=new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", orderCode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/transactionclear/payment/query/ordercode--RESULT================"+result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("resp_message", "没有该订单信息");
			return map;
		}
		bankCard = resultObj.getString("bankcard"); 
		amount = resultObj.getString("amount"); 
		rate = resultObj.getString("rate"); 
		extraFee = resultObj.getString("extraFee"); 
		userId = resultObj.getString("userid"); 
		
		if(bankCard == null || bankCard.equalsIgnoreCase("")){
			log.info("没有银行卡");
			return null;
		}
		
		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userId);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jfapi");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}
		String respcode = jsonObject.getString("resp_code");
		if (!"000000".equals(respcode)) {

			map.put("resp_code", "failed");
			map.put("channel_type", "jfapi");
			map.put("resp_message", "没有结算卡");
			return map;
		}
		// 默认提现卡卡号
		String cardNo = resultObj.getString("cardNo");
		String bankName = resultObj.getString("bankName");
		
		restTemplate=new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================"+result);
		try {
			jsonObject =  JSONObject.fromObject(result);
			resultObj  =  jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询信用卡出错");
			map.put("resp_code", "failed");
			map.put("resp_message", "查询信用卡有误");
			return map;
		}
		
		phone = resultObj.getString("phone"); //预留信用卡手机号码
		certId = resultObj.getString("idcard");//身份证号
		userName = resultObj.getString("userName");//用户姓名
		//userId = String.valueOf(resultObj.getLong("userId"));//用户ID
		
		JFApiRegister jfApiRegister = new JFApiRegister();
		String token = "";
		try {
			jfApiRegister = topupPayChannelBusiness.getJFApiRegister(bankCard);
			token = jfApiRegister.getToken();
		} catch (Exception e) {
			log.error("根据银行卡查询商户开通信息异常"+e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jfapi");
			map.put("resp_message", "查询商户开通信息异常");
			return map;
		}
		
		//手续费
		BigDecimal bigamount = new BigDecimal(amount);
		BigDecimal bigrate = new BigDecimal(rate);
		BigDecimal bigextraFee = new BigDecimal(extraFee);
		//Bigcecimal类型的运算
		BigDecimal multiply = bigamount.multiply(bigrate);
				
		//小数点后2位向上进1位
		BigDecimal setScale = multiply.setScale(2, RoundingMode.CEILING);
		BigDecimal add = setScale.add(bigextraFee);

		String fee = new BigDecimal(add+"").multiply(new BigDecimal("100")).setScale(0).toString();
		
		log.info("手续费======fee"+fee);
		//交易金额变成以分为单位
		String Amount = new BigDecimal(amount).multiply(new BigDecimal("100")).setScale(0).toString();
		
		//消费短信接口的交易代码
		String txnCode = "402001";
		String api = "/rest/api/" + txnCode;

		JSONObject dto = new JSONObject();

		dto.put("token", token);
		dto.put("txnAmt", Amount);//交易金额
		dto.put("cardHolderName", userName);//持卡人姓名
		dto.put("mobile", phone);//支付卡预留手机号
		dto.put("idCard", certId);//身份证号码
		dto.put("inBankCardNo", cardNo);// 入账卡卡号
		dto.put("inBankName", bankName);// 入账卡银行名称
		dto.put("fee", fee);// 手续费
		dto.put("remark", "充值缴费");// 商品名称
		dto.put("backUrl", ipAddress+"/v1.0/paymentchannel/topup/jfapi/notify_call");//后台通知地址
		
		dto.put("head", this.getHead(orderCode, partnerNo, txnCode));
		log.info("dto======" + dto);
		String execute = this.execute(Key, JFurl, api, dto.toString(), partnerNo, orderCode);
		log.info(execute);

		String res;
		// 返回状态码
		String respCode;
		String respMsg;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			log.info("hahahha=========" + resJson);
			String sign = resJson.getString("signature");
			log.info("hahahha=========" + sign);
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));
			log.info("hahahha=========" + res);

			com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(res);

			com.alibaba.fastjson.JSONObject head = json.getJSONObject("head");
			respCode = head.getString("respCode");
			respMsg = head.getString("respMsg");
		} catch (Exception e1) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jfapi");
			map.put("resp_message", "亲,失败啦");
			return map;
		}
		
		if("000000".equals(respCode)){
			map.put("resp_code", "success");
			map.put("channel_type", "jfapi");
			return map;
		}
		
		return null;
	}
	
	
	
	//消费接口
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/paymentchannel/topup/jfapi/pay")
	public @ResponseBody Object jfapipay(HttpServletRequest request,
			 @RequestParam(value = "ordercode") String orderCode,
			 @RequestParam(value = "smsCode") String smsCode
			 )
			throws Exception {
		log.info("开始进入消费接口=====================");
//		银行卡号
		String bankCard = "";
//		持卡人姓名
		String userName = "";
//		手机号
		String phone = "";
//		身份证号
		String certId = "";
//		用户Id
		String userId = "";
//		费率
		String rate = "";
		//额外费用
		String extraFee = "";  
		String amount = "";
		
		Map<String,String> map = new TreeMap<String,String>();
		RestTemplate restTemplate=new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", orderCode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/transactionclear/payment/query/ordercode--RESULT================"+result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("resp_message", "没有该订单信息");
			return map;
		}
		
		//银行卡(充值卡)
		bankCard = resultObj.getString("bankcard");
		amount = resultObj.getString("amount"); 
		JFApiRegister jfApiRegister = new JFApiRegister();
		String token = "";
		try {
			jfApiRegister = topupPayChannelBusiness.getJFApiRegister(bankCard);
			token = jfApiRegister.getToken();
		} catch (Exception e) {
			log.error("根据银行卡查询商户开通信息异常"+e);
			map.put("resp_code", "failed");
			map.put("channel_type", "jfapi");
			map.put("resp_message", "查询商户开通信息异常");
			return map;
		}
		
		//交易金额变成以分为单位
		String Amount = new BigDecimal(amount).multiply(new BigDecimal("100")).setScale(0).toString();
		
		//消费短信接口的交易代码
		String txnCode = "402002";
		String api = "/rest/api/" + txnCode;

		JSONObject dto = new JSONObject();

		dto.put("token", token);
		dto.put("txnAmt", Amount);//交易金额
		dto.put("smsCode", smsCode);//短信验证码

		dto.put("head", this.getHead(orderCode, partnerNo, txnCode));
		log.info("dto======" + dto);
		String execute = this.execute(Key, JFurl, api, dto.toString(), partnerNo, orderCode);
		log.info(execute);

		String res;
		// 返回状态码
		String respCode = null;
		String respMsg;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			log.info("hahahha=========" + resJson);
			String sign = resJson.getString("signature");
			log.info("hahahha=========" + sign);
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));
			log.info("hahahha=========" + res);

			com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(res);

			com.alibaba.fastjson.JSONObject head = json.getJSONObject("head");
			respCode = head.getString("respCode");
			respMsg = head.getString("respMsg");
		} catch (Exception e1) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jfapi");
			map.put("resp_message", "亲,失败啦");
			return map;
		}
		
		if("000000".equals(respCode)){
			
			map.put("resp_code", "success");
			map.put("channel_type", "jfapi");
			map.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/sdjpaysuccess");
			return map;
		}else{
			map.put("resp_code", "failed");	
			map.put("channel_type", "jfapi");
			map.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/sdjpayerror");
			return map;
		}
		
		
	}
	
	
	
	
	@RequestMapping(method=RequestMethod.GET,value="/v1.0/paymentchannel/topup/jfapipay")
	public  String returnjfapipay(HttpServletRequest request, HttpServletResponse response, Model model)throws IOException {
		// 设置编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String ordercode = request.getParameter("ordercode");

		model.addAttribute("ordercode", ordercode);
		
		return "jfapipaymessage";
	}
	
	
	
	// 前端开通成功异步通知
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfapi/openfront/notify_call")
	public Object quickPayCallback(HttpServletRequest request,HttpServletResponse response,
			@RequestParam String encryptData,
            @RequestParam String signature
			
	) throws Exception {
		
		  Map<String, String>  map = new HashMap<String, String>();
		  log.info("进来了");
		  String dataPlain = AES.decode(Base64.decode(encryptData),Key.substring(0,16));
		  log.info("前端开通回调：dataPlain: {} " ,dataPlain);
		  String checkSign = DigestUtils.sha1Hex(encryptData + Key.substring(16));

		  log.info("前端开通回调：checkSign: {} " , checkSign);

		  
		  if(!Objects.equal(signature,checkSign)){
		         log.error("签名验证失败");
		  }
		  
		  com.alibaba.fastjson.JSONObject parseObject = JSON.parseObject(dataPlain);
		  log.info("parseObject==========="+parseObject);
		  
		  com.alibaba.fastjson.JSONObject jsonObject2 = parseObject.getJSONObject("head");
		  
		  String accNo = parseObject.getString("accNo");
		  log.info("accNo======"+accNo);
		  
		  String token = parseObject.getString("token");
		  log.info("token======"+token);
		  
		  String respMsg = jsonObject2.getString("respMsg");
		  log.info("respMsg======"+respMsg); 
		  String respCode = jsonObject2.getString("respCode");
		  log.info("respCode======"+respCode);
		  String orderId = jsonObject2.getString("orderId");
		  log.info("orderId======"+orderId);
		 
		  if("开通成功".equals(respMsg)&&"000000".equals(respCode)){
			 
			  RestTemplate restTemplate=new RestTemplate();
			  URI uri = util.getServiceUrl("transactionclear", "error url request!");
			  String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
			  MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
			  requestEntity.add("order_code", orderId);
			  String result = restTemplate.postForObject(url, requestEntity, String.class);
			  log.info("RESULT================"+result);
			  JSONObject jsonObject = null;
			  JSONObject resultObj = null;
			  try {
				  jsonObject = JSONObject.fromObject(result);
				  resultObj = jsonObject.getJSONObject("result");
			  } catch (Exception e) {
				  log.error("查询订单信息出错");
			  }
			  
			  String userId = resultObj.getString("userid");
			  
			  JFApiRegister jfApiRegister = new JFApiRegister();
			  jfApiRegister.setUserId(Long.parseLong(userId));
			  jfApiRegister.setBankCard(accNo);
			  jfApiRegister.setToken(token);
			  
			  topupPayChannelBusiness.createJFApiRegister(jfApiRegister);
			  
			  log.info("前端开通数据保存成功");
			  
			  response.getWriter().write("000000");
			  
			  /*log.info("准备跳转=====");
			  Map maps = new HashMap();
			  maps.put("resp_code", "success");
			  maps.put("channel_type", "jfapi");
			  maps.put("redirect_url", ipAddress+"/v1.0/paymentchannel/topup/jfapipay?ordercode="+orderId);
			  return maps; */      
			  
		  }
		  
		return null;  
		  
	}
	
	
	//消费接口回调
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/jfapi/notify_call")
	public void jfapipayCallback(HttpServletRequest request,HttpServletResponse response,
			@RequestParam String encryptData,
            @RequestParam String signature
			
	) throws Exception {
		
		  log.info("进来了");
		  String dataPlain = AES.decode(Base64.decode(encryptData),Key.substring(0,16));
		  log.info("消费回调：dataPlain: {} " ,dataPlain);
		  String checkSign = DigestUtils.sha1Hex(encryptData + Key.substring(16));

		  log.info("消费回调：checkSign: {} " , checkSign);

		  
		  if(!Objects.equal(signature,checkSign)){
		         log.error("签名验证失败");
		  }
		  
		  com.alibaba.fastjson.JSONObject parseObject = JSON.parseObject(dataPlain);
		  log.info("parseObject==========="+parseObject);
		  
		  com.alibaba.fastjson.JSONObject jsonObject2 = parseObject.getJSONObject("head");
		  
		  String respCode = jsonObject2.getString("respCode");
		  log.info("respCode======"+respCode);
		  String orderId = jsonObject2.getString("orderId");
		  log.info("orderId======"+orderId);
		   
		  try {
				Log.setLogFlag(true);
				Log.println("---交易： 订单结果异步通知-------------------------");

				log.info("交易： 订单结果异步通知===================");
				if("success".equals(respCode)){ // 订单已支付;

					// 1、检查Amount和商户系统的订单金额是否一致
					// 2、订单支付成功的业务逻辑处理请在本处增加（订单通知可能存在多次通知的情况，需要做多次通知的兼容处理）；
					// 3、返回响应内容

					synchronized (this) {
						// **更新订单状态*//*
						// **调用下单，需要得到用户的订单信息*//*
						RestTemplate restTemplate = new RestTemplate();

						URI uri = util.getServiceUrl("transactionclear", "error url request!");
						String url = uri.toString() + "/v1.0/transactionclear/payment/update";

						// **根据的用户手机号码查询用户的基本信息*//*
						MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
						requestEntity.add("status", "1");
						requestEntity.add("order_code", orderId);
						String result = restTemplate.postForObject(url, requestEntity, String.class);

						log.info("订单状态修改成功===================");

						// **判断是否有外放的通道的处理， 如果有那么继续回调外放哦*//*
						uri = util.getServiceUrl("transactionclear", "error url request!");
						url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";

						requestEntity = new LinkedMultiValueMap<String, String>();
						requestEntity.add("order_code", orderId);
						result = restTemplate.postForObject(url, requestEntity, String.class);

						JSONObject jsonObject = JSONObject.fromObject(result);
						JSONObject resultObj = jsonObject.getJSONObject("result");
						String outMerOrdercode = resultObj.getString("outMerOrdercode");
						String orderdesc = resultObj.getString("desc");
						String phone = resultObj.getString("phone");
						String tranamount = resultObj.getString("amount");
						String channelTag = resultObj.getString("channelTag");
						String notifyURL = resultObj.getString("outNotifyUrl");
						if (outMerOrdercode != null && !outMerOrdercode.equalsIgnoreCase("")) {
							uri = util.getServiceUrl("channel", "error url request!");
							url = uri.toString() + "/v1.0/channel/callback/yilian/notify_call";
							requestEntity = new LinkedMultiValueMap<String, String>();
							requestEntity.add("merchant_no", phone);
							requestEntity.add("amount", tranamount);
							requestEntity.add("channel_tag", channelTag);
							requestEntity.add("order_desc", URLEncoder.encode(orderdesc, "UTF-8"));
							requestEntity.add("order_code", outMerOrdercode);
							requestEntity.add("sys_order", orderId);
							requestEntity.add("notify_url", URLEncoder.encode(notifyURL, "UTF-8"));
							result = restTemplate.postForObject(url, requestEntity, String.class);
						}

						log.info("订单已支付!");
						response.getWriter().write("000000");
					}
				} else {
					// 1、订单支付失败的业务逻辑处理请在本处增加（订单通知可能存在多次通知的情况，需要做多次通知的兼容处理，避免成功后又修改为失败）；
					// 2、返回响应内容

					log.info("订单支付失败!");
				}
			} catch (Exception e) {
				log.error(e.getMessage());
			}
			log.info("-----处理完成----");
	}
	
	
	
	
	//===================================================
	
	protected String execute(String key, String url, String api, String dataJson, String partnerNo, String orderId) {

		System.out.println("============ 请求报文:" + dataJson);
		String signKey = key.substring(16);
		String dataKey = key.substring(0, 16);
		String sign = DigestUtils.sha1Hex(dataJson + signKey);

		Map<String, String> params = Maps.newHashMap();
		params.put("encryptData", Base64.encode(AES.encode(dataJson, dataKey)));
		params.put("signData", sign);
		params.put("orderId", orderId);
		params.put("partnerNo", partnerNo);
		params.put("ext", "to be or not to be");

		System.out.println("encryptData : " + params.get("encryptData"));
		System.out.println("sign : " + params.get("sign"));
		System.out.println("partnerNo : " + params.get("partnerNo"));

		System.out.println("============ 请求地址:" + url + api);
		try {
			byte[] resByte = HttpClient4Util.getInstance().doPost(url + api, null, params);
			String resStr = new String(resByte, UTF_8);
			System.out.println("============ 返回报文原文:" + resStr);

			return resStr;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public Object getHead(String ordercode, String partnerNo, String txnCode) {
		JSONObject head = new JSONObject();
		head.put("version", "1.0.0");
		head.put("charset", "UTF-8");
		head.put("partnerNo", partnerNo); // 合作方标识号
		head.put("txnCode", txnCode); // 交易代码
		head.put("orderId", ordercode); // 订单号
		head.put("reqDate", DateTime.now().toString("yyyyMMdd"));
		head.put("reqTime", DateTime.now().toString("yyyyMMddHHmmss"));
		return head;
	}

}
